package com.reactim.message.config.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * 批次大小数组验证器
 */
public class BatchSizesValidator implements ConstraintValidator<ValidBatchSizes, int[]> {
    
    private int minSize;
    private int maxSize;
    private int minLength;
    
    @Override
    public void initialize(ValidBatchSizes constraintAnnotation) {
        this.minSize = constraintAnnotation.minSize();
        this.maxSize = constraintAnnotation.maxSize();
        this.minLength = constraintAnnotation.minLength();
    }
    
    @Override
    public boolean isValid(int[] values, ConstraintValidatorContext context) {
        if (values == null) {
            return true; // 让@NotNull处理null值
        }
        
        // 检查数组长度
        if (values.length < minLength) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                String.format("批次大小数组长度必须至少为%d，当前长度: %d", minLength, values.length)
            ).addConstraintViolation();
            return false;
        }
        
        // 检查每个值的有效性
        for (int i = 0; i < values.length; i++) {
            int value = values[i];
            if (value < minSize || value > maxSize) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(
                    String.format("批次大小[%d]必须在%d到%d之间，当前值: %d", i, minSize, maxSize, value)
                ).addConstraintViolation();
                return false;
            }
        }
        
        return true;
    }
}